package com.example.musicrunner.client;

import java.util.ArrayList;

import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class WebAPIActivity extends AsyncTask<String, Integer, String> {

	private ListDataActivity activity;

	@Override
    protected void onPreExecute() {
        super.onPreExecute(); 
    }

    @Override
    protected String doInBackground(String... params) {
        try {
            String result = LastFMKey.downloadFromServer(params);
            return result;
        } catch (Exception e) {
            return new String();
        }
    }
    
    @Override
    protected void onPostExecute(String result)  {
    	
    	ArrayList<TrackData> trackdata = new ArrayList<TrackData>();
        try {
			JSONObject respObj = new JSONObject(result);
			JSONObject topTracksObj = respObj.getJSONObject("toptracks");
			JSONArray tracks = topTracksObj.getJSONArray("track");
			
			for(int i=0; i<tracks.length(); i++) {
				
				JSONObject track = tracks.getJSONObject(i);	
				String trackName = track.getString("trackName");
				String trackUrl = track.getString("trackUrl");
				JSONObject artistObj = track.getJSONObject("artist");
				String artistName = artistObj.getString("artistName");

				trackdata.add(new TrackData(trackName,artistName, trackUrl));				
			}
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.activity.setTracks(trackdata);
             
    }
}